package main

import (
	"context"
	"exchange-info/persistence"
	"fmt"

	"gitee.com/hacker61/go-binance/v2"

	//"gitee.com/hacker61/go-binance/v2/futures"
	"strings"
)

func init() {
	conf_init()
}

func parsePrecision(stepSize string) int {
	index := strings.Index(stepSize, "1")
	if index > 0 {
		index = index - 1
	}
	return index
}

func main() {
	ppersistence := persistence.PersistenceMysql{}.Init(conf.MysqlOpt.Host, conf.MysqlOpt.Port, conf.MysqlOpt.User, conf.MysqlOpt.Passwd, conf.MysqlOpt.DBName)
	client := binance.NewClient("", "")
	exchangeInfo, err := client.NewExchangeInfoService().Do(context.Background())
	if err != nil {
		panic(err)
	}
	for _, symbolExchangeInfo := range exchangeInfo.Symbols {
		if strings.HasSuffix(symbolExchangeInfo.Symbol, "USDT") {
			lotSizeFilter := symbolExchangeInfo.LotSizeFilter()
			priceFilter := symbolExchangeInfo.PriceFilter()
			marketLotSizeFilter := symbolExchangeInfo.MarketLotSizeFilter()
			if lotSizeFilter == nil || priceFilter == nil || marketLotSizeFilter == nil {
				continue
			}
			lotPrecision := parsePrecision(lotSizeFilter.StepSize)
			pricePrecision := parsePrecision(priceFilter.TickSize)
			marketLotPrecision := parsePrecision(marketLotSizeFilter.StepSize)
			err := ppersistence.InsertOrUpdateSpotExchangeInfo(symbolExchangeInfo.Symbol, pricePrecision, lotPrecision, marketLotPrecision)
			if err != nil {
				fmt.Println(err)
			}
		}
	}

	futuresClient := binance.NewFuturesClient("", "")
	fExchangeInfo, err := futuresClient.NewExchangeInfoService().Do(context.Background())
	if err != nil {
		panic(err)
	}
	for _, symbolExchangeInfo := range fExchangeInfo.Symbols {
		if strings.HasSuffix(symbolExchangeInfo.Symbol, "USDT") {
			lotSizeFilter := symbolExchangeInfo.LotSizeFilter()
			priceFilter := symbolExchangeInfo.PriceFilter()
			marketLotSizeFilter := symbolExchangeInfo.MarketLotSizeFilter()
			if lotSizeFilter == nil || priceFilter == nil || marketLotSizeFilter == nil {
				continue
			}
			lotPrecision := parsePrecision(lotSizeFilter.StepSize)
			pricePrecision := parsePrecision(priceFilter.TickSize)
			marketLotPrecision := parsePrecision(marketLotSizeFilter.StepSize)
			err := ppersistence.InsertOrUpdateFuturesExchangeInfo(symbolExchangeInfo.Symbol, pricePrecision, lotPrecision, marketLotPrecision)
			if err != nil {
				fmt.Println(err)
			}
		}
	}
}
